import { updateUserUsingPost } from "@/api/userController";
import { ProColumns, ProTable } from "@ant-design/pro-components";
import { message, Modal, Avatar } from "antd";
import React from "react";

interface Props {
  oldData?: API.User;
  visible: boolean;
  columns: ProColumns<API.User>[];
  onSubmit: (values: API.UserAddRequest) => void;
  onCancel: () => void;
}

const VALIDATE_REGEX = {
  USERNAME: /^[\u4e00-\u9fa5a-zA-Z0-9_-]{2,16}$/,
  ACCOUNT: /^[a-zA-Z0-9_]{4,20}$/,
  PROFILE: /^[\s\S]{1,200}$/,
};

const handleUpdate = async (fields: API.UserUpdateRequest) => {
  const validateFields = () => {
    if (
      !fields.userName ||
      !VALIDATE_REGEX.USERNAME.test(fields.userName.trim())
    ) {
      message.error("请输入2-16位有效用户名（可包含中英文、数字、下划线）");
      return false;
    }
    if (
      // @ts-ignore
      !fields.userAccount ||
      // @ts-ignore
      !VALIDATE_REGEX.ACCOUNT.test(fields.userAccount.trim())
    ) {
      message.error("请输入4-20位有效账号（字母、数字、下划线）");
      return false;
    }
    if (
      !fields.userProfile ||
      !VALIDATE_REGEX.PROFILE.test(fields.userProfile.trim())
    ) {
      message.error("简介长度应在1-200个字符之间");
      return false;
    }
    return true;
  };

  if (!validateFields()) return false;

  const hide = message.loading("正在更新");
  try {
    await updateUserUsingPost(fields);
    hide();
    message.success("更新成功");
    return true;
  } catch (error: any) {
    hide();
    message.error("更新失败，" + error.message);
    return false;
  }
};

const UpdateModal: React.FC<Props> = (props) => {
  const { oldData, visible, columns, onSubmit, onCancel } = props;

  // 修改头像列的渲染方式
  const modifiedColumns = columns.map((column) => {
    if (column.dataIndex === "userAvatar") {
      return {
        ...column,
        // @ts-ignore
        renderFormItem: (_, __, form) => (
          <Avatar
            src={form.getFieldValue("userAvatar")}
            size={128}
            style={{ display: "block" }}
          />
        ),
        // @ts-ignore
        render: (text) => <Avatar src={text} size={64} />,
      };
    }
    return column;
  });

  if (!oldData) {
    return <></>;
  }

  return (
    <Modal
      destroyOnClose
      title={"更新"}
      open={visible}
      footer={null}
      onCancel={onCancel}
    >
      <ProTable
        type="form"
        columns={modifiedColumns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (values: API.UserAddRequest) => {
          const success = await handleUpdate({
            ...values,
            id: oldData?.id as any,
          } as any);
          if (success) {
            onSubmit?.(values);
          }
        }}
      />
    </Modal>
  );
};

export default UpdateModal;
